<template>
  <a-modal
    :zIndex="zIndex"
    :title="title"
    :visible="visible"
    @cancel="handleCancel"
    width="750px"
    :cancelText="$t('关闭')"
    :confirmLoading="confirmLoading"
    v-drag
  >
    <template slot="footer">
      <a-row :gutter="24">
        <a-col :span="12">
          <div style="text-align: left" v-if="!dataForm.id">
            <a-checkbox v-model="isContinue" @change="changeAddState"></a-checkbox> {{ $t('连续添加') }}
          </div>
        </a-col>
        <a-col :span="12">
          <a-button @click="handleCancel" :disabled="confirmLoading">{{ $t('取消') }}</a-button>
          <a-button type="primary" @click="handleOk" v-if="!disable" :disabled="confirmLoading">{{
            $t('保存')
          }}</a-button>
        </a-col>
      </a-row>
    </template>
    <div style="max-height: 500px; overflow-y: auto">
      <a-form-model
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        v-enterToNext
      >
        <a-form-model-item
          prop="code"
          style="margin-bottom: 10px"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label="$t('商品编码')"
        >
          <a-input v-model="dataForm.code" ref="code" :disabled="disable"></a-input>
        </a-form-model-item>
        <a-form-model-item
          prop="name"
          style="margin-bottom: 10px"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label="$t('商品名称')"
        >
          <a-input v-model="dataForm.name" :disabled="disable"></a-input>
        </a-form-model-item>
        <a-form-model-item
          prop="kind"
          style="margin-bottom: 10px"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label="$t('商品分类')"
        >
          <a-tree-select
            show-search
            :filterTreeNode="filterTreeNode"
            :disabled="disable"
            allowClear
            v-model="dataForm.kind"
            :dropdownStyle="{ maxHeight: '250px', overflow: 'auto' }"
            :tree-data="treeData"
            :placeholder="$t('请选择')"
            :getPopupContainer="triggerNode => { return triggerNode.parentNode || document.body }"
          />
        </a-form-model-item>
        <a-form-model-item
          prop="cost"
          style="margin-bottom: 10px"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label="$t('参考成本')"
        >
          <a-input-number v-model="dataForm.cost" :disabled="disable"

                          :formatter="formatter"
                                  :parser="parser"
                          style="width: 100%;"
                          :precision="2"
          ></a-input-number>
        </a-form-model-item>
        <a-form-model-item
          prop="price"
          style="margin-bottom: 10px"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label="$t('售价')"
        >
          <a-input-number v-model="dataForm.price" :disabled="disable" @change="changePrice"

                          :formatter="formatter"
                                  :parser="parser"
                          style="width: 100%;"
                          :precision="2"
          ></a-input-number>
        </a-form-model-item>
        <a-form-model-item
          prop="allowTax"
          style="margin-bottom: 10px"
          v-if="taxSetting == 2"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label="$t('其中税费')"
        >
          {{dataForm.taxPrice}}
        </a-form-model-item>
        <a-form-model-item
          prop="realCoin"
          style="margin-bottom: 10px"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label="$t('币值')"
        >
          <a-input-number v-model="dataForm.realCoin" :disabled="disable"

                          :formatter="formatter"
                                  :parser="parser"
                          style="width: 100%;"
          ></a-input-number>
        </a-form-model-item>
        <a-form-model-item
          prop="allowTax"
          style="margin-bottom: 10px"
          v-if="taxSetting == 1"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label="$t('销售设置')"
        >
          <a-checkbox :checked="dataForm.allowTax == 1" :disabled="disable" @change="changeSelectState">{{ $t('销售加税') }}</a-checkbox>
        </a-form-model-item>
        <a-form-model-item prop="state" :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('上架状态')">
          <a-radio-group v-model="dataForm.state" ref="state" :disabled="disable">
            <a-radio value="Y">{{ $t('上架') }}</a-radio>
            <a-radio value="N">{{ $t('下架') }}</a-radio>
          </a-radio-group>
        </a-form-model-item>
      </a-form-model>
    </div>
  </a-modal>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import {formatter, parser} from "@api/comm";

export default {
  name: 'TimeLimitCoinModal',
  components: {},
  data() {
    return {
      formatter,
      parser,
      zIndex: 1001,
      form: this.$form.createForm(this),
      title: '',
      visible: false,
      confirmLoading: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      dataForm: {
        code: '',
        name: '',
        allowOuts: '',
        allowWarns: '',
        warnNum: 0,
        verifyType: '1',
        allowTax: 1,
        allowMemberDiscounts: '',
        allowSale: 'Y',
        state: '',
        allowMemberType: '',
        allowDeviceType: '',
        allowDevice: '',
        allowGame: '',
        form: '', //形态
        validityType: '0',
      },
      labelCol: {
        xs: { span: 20 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 20 },
        sm: { span: 15 },
      },
      rules: {
        name: [{ required: true, message: this.$t('请输入卖品名称') }],
        kind: [{ required: true, message: this.$t('请选择卖品分类') }],
        realCoin: [
          { required: true, message: this.$t('请输入币值') },
          { pattern: /^\d+.?\d{0,2}$/, message: this.$t('小数点后最多输入两位') },
        ],
        price: [
          { required: true, message: this.$t('请输入售价') },
          { pattern: /^\d+.?\d{0,2}$/, message: this.$t('小数点后最多输入两位') },
        ],
      },
      url: {
        add: '/goods/bisGoodsInfor/add',
        edit: '/goods/bisGoodsInfor/edit',
        importExcelUrl: '/sys/common/upload',
      },
      disable: false,
      treeData: [],
      islimitValid: false,
      isContinue: true,
      selectAll: false,
      taxSetting: 0,
    }
  },
  mounted() {},
  methods: {
    add(value) {
      this.visible = true
      this.isContinue = localStorage.getItem('goodsAddInfo')
        ? JSON.parse(localStorage.getItem('goodsAddInfo')).state
        : true
      this.selectAll = false
      this.dataForm = {
        code: '',
        name: '',
        allowOut: 'Y',
        allowWarns: '',
        warnNum: 0,
        verifyType: '1',
        cost: 0,
        allowTax: 1,
        allowMemberDiscount: 'Y',
        allowSale: 'Y',
        state: 'Y',
        allowMemberType: '',
        allowDevice: '',
        allowDeviceType: '',
        allowGame: '',
        form: value,
        presentCoin: '0',
        realCoin: '',
        species: '1',
        validityType: '0',
      }
      this.edit(this.dataForm)
    },
    edit(record, state) {
      this.disable = state
      this.taxSetting = localStorage.getItem('taxSetting')
      this.select()
      this.visible = true
      this.$nextTick(() => {
        this.dataForm = Object.assign({}, record)
      })
    },
    filterTreeNode(inputValue, treeNode) {
      // 假设输入格式为 "级别:关键词" 如 "2:电器"
      const match = inputValue.match(/([123]):(.+)/)
      if (match) {
        const level = parseInt(match[1])
        const keyword = match[2]
        const nodeLevel = this.getNodeLevel(treeNode)
        
        if (nodeLevel !== level) return false
        return treeNode.data.props.title.includes(keyword)
      }
      
      // 默认搜索
      return treeNode.data.props.title.includes(inputValue)
    },
    getNodeLevel(node) {
      let level = 1
      let parent = node.parent
      while (parent) {
        level++
        parent = parent.parent
      }
      return level
    },
    select() {
      let that = this
      let param = {}
      param.pageNo = 1
      param.pageSize = 9999
      param.column = 'sort'
      param.order = 'asc'
      getAction('/goods/bisGoodsKind/rootList', param).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.id = '' + col.id
              col.pid = '' + col.pid
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChild(col)
              }
            })
            that.treeData = that.getDataByResult(res.result.records)
          } else {
            that.treeData = []
          }
        } else {
          that.$alert(res.message, that.$t('提示'), {
            confirmButtonText: that.$t('确定'),
            callback: (action) => {},
          })
        }
      })
    },
    getHasChild(record) {
      let that = this
      let query = {}
      query.pageNo = 1
      query.pageSize = 9999
      query.pid = record.id
      getAction('/goods/bisGoodsKind/rootList', query).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.pid = '' + col.pid
              col.id = '' + col.id
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChild(col)
              }
            })
            record.children = that.getDataByResult(res.result.records)
            that.treeData = [...that.treeData]
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    getDataByResult(result) {
      return result.map((item) => {
        return item
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      let that = this
      let querydata = {}
      that.$refs.dataForm.validate((valid) => {
        if (valid) {
          querydata = that.dataForm
          let httpurl = ''
          let method = ''
          if (!that.dataForm.id) {
            httpurl += that.url.add
            method = 'post'
          } else {
            httpurl += that.url.edit
            method = 'put'
          }
          that.confirmLoading = true
          httpAction(httpurl, querydata, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                if (that.dataForm.id || !that.isContinue) {
                  that.close()
                } else {
                  that.initDataForm()
                }
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    changeAddState() {
      localStorage.setItem('goodsAddInfo', JSON.stringify({ state: this.isContinue }))
    },
    initDataForm() {
      this.selectAll = false
      this.dataForm = {
        code: '',
        name: '',
        allowOut: 'Y',
        allowWarns: '',
        warnNum: 0,
        verifyType: '1',
        cost: 0,
        allowMemberDiscount: 'Y',
        allowSale: 'Y',
        state: 'Y',
        allowMemberType: '',
        allowDevice: '',
        allowDeviceType: '',
        allowGame: '',
        form: 17,
        presentCoin: '0',
        realCoin: '',
        species: '1',
        validityType: '0',
      }
      this.$refs.code.focus()
      this.edit(this.dataForm)
    },
    changeSelectState(e){
      this.$set(this.dataForm, "allowTax", e.target.checked ? 1 : 0)
    },
    changePrice() {
      if(this.taxSetting == 2){
        this.$set(this.dataForm,'taxPrice',(this.dataForm.price - (this.dataForm.price / ( 1 + localStorage.getItem('taxRate') / 100))).toFixed(2))
      }
    },
  },
}
</script>

<style scoped>
</style>